package com.tf.integrated.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ccssoft.m8.common.ccssoft.modules.util.EntityWrapperHandle;
import com.ccssoft.m8.common.web.BaseController;
import com.tf.integrated.entity.AdmininfoEntity;
import com.tf.integrated.entity.AuthorityInfoEntity;
import com.tf.integrated.entity.ClientInfoEntity;
import com.tf.integrated.service.AdmininfoService;
import com.tf.integrated.service.AuthorityInfoService;
import com.tf.integrated.service.ClientInfoService;
import com.xiaoleilu.hutool.codec.Base64;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 用户及权限接口
 *
 * @author allen
 * @date: 2020年9月14日上午10:56:20
 */
@Api(value = "用户及权限接口", description = "AdminInfoController")
@RestController
public class AdminInfoController extends BaseController {
    private final CacheManager singletonManager = CacheManager.create();

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private AdmininfoService<AdmininfoEntity> adminService;

    @Autowired
    private AuthorityInfoService<AuthorityInfoEntity> authorityService;

    @Autowired
    private ClientInfoService<ClientInfoEntity> clientService;

    @ApiOperation("用户登录")
    @PostMapping("/user/login")
    @CrossOrigin(origins = "*", maxAge = 86400)
    public JSONObject userLogin(@RequestBody JSONObject data) {
        JSONObject returnData = new JSONObject();
        if (data != null && data.size() > 0) {
            String user = data.getString("user");
            String password = data.getString("password");
            if (isExist(user) && isExist(password)) {
                EntityWrapperHandle<AdmininfoEntity> ew = new EntityWrapperHandle<AdmininfoEntity>();
                ew.eq("username", user);
                ew.eq("password", password);
                List<AdmininfoEntity> userlist = adminService.selectList(ew);
                if (null != userlist && userlist.size() > 0) {
                    String token = Base64.encode(getUUIDPrimaryKey() + "-" + userlist.get(0).getId().toString());
                    Cache memoryOnlyCache = new Cache(token, 5000, false, false, 18000, 3000);
                    singletonManager.addCache(memoryOnlyCache);
                    returnData.put("token", token);
                    returnData.put("id", userlist.get(0).getId());
                    returnData.put("name", userlist.get(0).getName());
                    returnData.put("authority", getJsonAuthority(userlist.get(0)));
                    int type = userlist.get(0).getType();
                    if (type == 2) {
                        int clientId = userlist.get(0).getClientid();
                        ClientInfoEntity clientInfoEntity = clientService.selectById(clientId);
                        if(clientInfoEntity!=null){
                            returnData.put("clientToken", clientInfoEntity.getToken());
                        }
                    }
                    returnData.put("type", type);
                }else{
                    returnData.put("message", "账号或密码错误");
                }
            }else{
                returnData.put("message", "账号或密码未输入");
            }
        }else{
            returnData.put("message", "参数不存在");
        }
        return returnData;
    }

    @ApiOperation("用户登出")
    @PostMapping("/user/logout")
    @CrossOrigin(origins = "*", maxAge = 86400)
    public JSONObject userLogout() {
        JSONObject returnData = new JSONObject();
        String token = request.getHeader("Login-Token");
        if (isExist(token)) {
            singletonManager.removeCache(token);
        }
        returnData.put("code", 200);
        return returnData;
    }

    @ApiOperation("新建用户")
    @PostMapping("/user")
    @CrossOrigin(origins = "*", maxAge = 86400)
    public JSONObject newUser(@RequestBody JSONObject data) {
        JSONObject returnData = new JSONObject();
        if (data != null && data.size() > 0) {
            String user = data.getString("user");
            String password = data.getString("password");
            String name = data.getString("name");
            String description = data.getString("description");
            int type = data.getIntValue("type");
            JSONArray aty = data.getJSONArray("authority");
            if (isExist(user) && isExist(password) && isExist(name) && isExist(description) && aty.size() == 5) {
                if(type==1){
                    EntityWrapperHandle<AdmininfoEntity> ew = new EntityWrapperHandle<AdmininfoEntity>();
                    ew.eq("username", user);
                    int count = adminService.selectCount(ew);
                    if (count == 0) {
                        AdmininfoEntity admininfoEntity = new AdmininfoEntity();
                        admininfoEntity.setUsername(user);
                        admininfoEntity.setPassword(password);
                        admininfoEntity.setOpen(1);
                        admininfoEntity.setType(type);
                        admininfoEntity.setRemarks(description);
                        admininfoEntity.setName(name);
                        setJsonAuthority(admininfoEntity, aty);
                        adminService.insert(admininfoEntity);
                        EntityWrapperHandle<AdmininfoEntity> ew2 = new EntityWrapperHandle<AdmininfoEntity>();
                        ew2.eq("username", user);
                        ew2.setSqlSelect("id");
                        List<AdmininfoEntity> list = adminService.selectList(ew2);
                        if (list != null && list.size() > 0) {
                            returnData.put("id", list.get(0).getId());
                        } else {
                            returnData.put("message", "创建账号失败");
                        }
                    } else {
                        returnData.put("message", "该账号已存在");
                    }
                }else if(type==2){
                    EntityWrapperHandle<AdmininfoEntity> ew = new EntityWrapperHandle<AdmininfoEntity>();
                    ew.eq("username", user);
                    int count = adminService.selectCount(ew);
                    if (count == 0) {
                        EntityWrapperHandle<ClientInfoEntity> ew0 = new EntityWrapperHandle<>();
                        ew0.orderDesc(Collections.singletonList("id"));
                        ew0.last("limit 1");
                        List<ClientInfoEntity> clientList = clientService.selectList(ew0);
                        String token = "";
                        if(clientList!=null&&clientList.size()>0){
                            token = createToken(clientList.get(0).getId()+1);
                        }else{
                            token = createToken(1);
                        }
                        ClientInfoEntity clientInfoEntity = new ClientInfoEntity();
                        clientInfoEntity.setClientname(RandomStringUtils.randomAlphabetic(8));
                        clientInfoEntity.setRemarks(RandomStringUtils.randomAlphabetic(8));
                        JSONArray devices = data.getJSONArray("devices");
                        if(devices!=null){
                            clientInfoEntity.setRelationdevice(devices.toJSONString());
                        }
                        clientInfoEntity.setToken(token);
                        if(clientService.insert(clientInfoEntity)){
                            EntityWrapperHandle<ClientInfoEntity> clients = new EntityWrapperHandle<>();
                            clients.eq("token",token);
                            List<ClientInfoEntity> client = clientService.selectList(clients);
                            if(client!=null&&client.size()>0){
                                AdmininfoEntity admininfoEntity = new AdmininfoEntity();
                                admininfoEntity.setClientid(client.get(0).getId());
                                admininfoEntity.setUsername(user);
                                admininfoEntity.setPassword(password);
                                admininfoEntity.setOpen(1);
                                admininfoEntity.setType(type);
                                admininfoEntity.setRemarks(description);
                                admininfoEntity.setName(name);
                                setJsonAuthority(admininfoEntity, aty);
                                adminService.insert(admininfoEntity);
                                EntityWrapperHandle<AdmininfoEntity> ew2 = new EntityWrapperHandle<AdmininfoEntity>();
                                ew2.eq("username", user);
                                ew2.setSqlSelect("id");
                                List<AdmininfoEntity> list = adminService.selectList(ew2);
                                if (list != null && list.size() > 0) {
                                    returnData.put("id", list.get(0).getId());
                                } else {
                                    returnData.put("message", "创建账号失败");
                                }
                            }else{
                                returnData.put("message", "创建账号失败");
                            }
                        }else{
                            returnData.put("message", "创建账号失败");
                        }
                    } else {
                        returnData.put("message", "该账号已存在");
                    }
                }else {
                    returnData.put("message", "参数错误");
                }
            } else {
                returnData.put("message", "参数错误");
            }
        }else{
            returnData.put("message", "参数不存在");
        }
        return returnData;
    }

    @ApiOperation("删除用户")
    @DeleteMapping("/user")
    @CrossOrigin(origins = "*", maxAge = 86400)
    public JSONObject deleteUser(@RequestParam Map<String, Object> data) {
        JSONObject returnData = new JSONObject();
        if (data != null && data.size() > 0) {
            String sid = (String) data.get("id");
            if (isExist(sid)&&isInteger(sid)) {
                int id = Integer.parseInt(sid);
                if (id > 0) {
                    AdmininfoEntity user = adminService.selectById(id);
                    if(user!=null){
                        if(user.getType() == 2){
                            clientService.deleteById(user.getClientid());
                        }
                        if(adminService.deleteById(id)){
                            returnData.put("code",200);
                        }else{
                            returnData.put("message", "删除失败");
                        }
                    }else{
                        returnData.put("message", "账号不存在");
                    }
                }else{
                    returnData.put("message", "id不正确");
                }
            } else {
                returnData.put("message", "id不存在");
            }
        }else{
            returnData.put("message", "参数不存在");
        }
        return returnData;
    }

    @ApiOperation("修改用户信息")
    @PutMapping("/user")
    @CrossOrigin(origins = "*", maxAge = 86400)
    public JSONObject changeUser(@RequestBody JSONObject data) {
        JSONObject returnData = new JSONObject();
        if (data != null && data.size() > 0) {
            int id = data.getIntValue("id");
            if (id > 0) {
                AdmininfoEntity user =  adminService.selectById(id);
                if(user!=null){
                    AdmininfoEntity admininfoEntity = new AdmininfoEntity();
                    admininfoEntity.setId(id);
                    admininfoEntity.setUpdatetime(new Date());
                    String password = data.getString("password");
                    if (isExist(password)) {
                        admininfoEntity.setPassword(password);
                    }
                    String description = data.getString("description");
                    if (isExist(description)) {
                        admininfoEntity.setRemarks(description);
                    }
                    String name = data.getString("name");
                    if (isExist(name)) {
                        admininfoEntity.setName(name);
                    }
                    JSONArray aty = data.getJSONArray("authority");
                    if (aty != null && aty.size() > 0) {
                        setJsonAuthority(admininfoEntity, aty);
                    }
                    if(user.getType() == 2){
                        JSONArray devices = data.getJSONArray("devices");
                        if(devices!=null){
                            ClientInfoEntity client = new ClientInfoEntity();
                            client.setId(user.getClientid());
                            client.setRelationdevice(devices.toJSONString());
                            clientService.updateById(client);
                        }
                    }
                    if(adminService.updateById(admininfoEntity)){
                        returnData.put("code",200);
                    }else{
                        returnData.put("message", "更新失败");
                    }
                }else{
                    returnData.put("message", "用户不存在");
                }
            } else {
                returnData.put("message", "id不正确");
            }
        }else{
            returnData.put("message", "参数不存在");
        }
        return returnData;
    }

    @ApiOperation("获取用户列表")
    @GetMapping("/user/list")
    @CrossOrigin(origins = "*", maxAge = 86400)
    public JSONObject userList(@RequestParam Map<String, Object> data) {
        JSONObject returnData = new JSONObject();
        EntityWrapperHandle<AdmininfoEntity> ew = new EntityWrapperHandle<AdmininfoEntity>();
        if (data != null && data.size() > 0) {
            String stype = (String) data.get("type");
            if (isExist(stype)&&isInteger(stype)) {
                int type = Integer.parseInt(stype);
                if (type > 0) {
                    ew.eq("type", type);
                }
            }
        }
        List<AdmininfoEntity> list = adminService.selectList(ew);
        int total = 0;
        JSONArray jsonArray = new JSONArray();
        if (list != null && list.size() > 0) {
            total = list.size();
            for (AdmininfoEntity admininfoEntity : list) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("id", admininfoEntity.getId());
                jsonObject.put("type", admininfoEntity.getType());
                jsonObject.put("name", admininfoEntity.getName());
                jsonObject.put("user", admininfoEntity.getUsername());
                jsonObject.put("description", admininfoEntity.getRemarks());
                jsonArray.add(jsonObject);
            }
        }
        returnData.put("code", 200);
        returnData.put("total", total);
        returnData.put("list", jsonArray);
        return returnData;
    }

    @ApiOperation("获取用户信息")
    @GetMapping("/user")
    @CrossOrigin(origins = "*", maxAge = 86400)
    public JSONObject userInfo(@RequestParam Map<String, Object> data) {
        JSONObject returnData = new JSONObject();
        if (data != null && data.size() > 0) {
            String sid = (String) data.get("id");
            if (isExist(sid)&&isInteger(sid)) {
                int id = Integer.parseInt(sid);
                if (id > 0) {
                    AdmininfoEntity user = adminService.selectById(id);
                    if (user != null) {
                        returnData.put("id", user.getId());
                        returnData.put("type", user.getType());
                        returnData.put("name", user.getName());
                        returnData.put("user", user.getUsername());
                        returnData.put("description", user.getRemarks());
                        if(user.getType() == 2){
                            ClientInfoEntity client = clientService.selectById(user.getClientid());
                            returnData.put("devices",JSONArray.parseArray(client.getRelationdevice()));
                        }
                    }else{
                        returnData.put("message", "用户不存在");
                    }
                }else{
                    returnData.put("message", "id错误");
                }
            }else{
                returnData.put("message", "id不存在");
            }
        }else{
            returnData.put("message", "参数不存在");
        }
        return returnData;
    }

    @ApiOperation("获取权限列表")
    @GetMapping("/authorityList")
    @CrossOrigin(origins = "*", maxAge = 86400)
    public JSONArray getAuthorityList(@RequestParam Map<String, Object> data) {
        JSONArray returnData = new JSONArray();
        List<AuthorityInfoEntity> list = authorityService.selectList(new EntityWrapperHandle<AuthorityInfoEntity>());
        if(list!=null&&list.size()>0){
            if (data != null && data.size() > 0) {
                String sid = (String) data.get("id");
                if (isExist(sid)&&isInteger(sid)) {
                    int id = Integer.parseInt(sid);
                    if (id > 0) {
                        AdmininfoEntity admininfoEntity = adminService.selectById(id);
                        if (admininfoEntity != null) {
                            if (admininfoEntity.getAuthority1() > 0) {
                                returnData.add(getAuthority(1, list));
                            }
                            if (admininfoEntity.getAuthority2() > 0) {
                                returnData.add(getAuthority(2, list));
                            }
                            if (admininfoEntity.getAuthority3() > 0) {
                                returnData.add(getAuthority(3, list));
                            }
                            if (admininfoEntity.getAuthority4() > 0) {
                                returnData.add(getAuthority(4, list));
                            }
                            if (admininfoEntity.getAuthority5() > 0) {
                                returnData.add(getAuthority(5, list));
                            }
                        }
                    }
                }
            } else {
                for (AuthorityInfoEntity authorityInfoEntity : list) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("id", authorityInfoEntity.getAid());
                    jsonObject.put("name", authorityInfoEntity.getName());
                    jsonObject.put("description", authorityInfoEntity.getDescription());
                    jsonObject.put("model", JSONArray.parseArray(authorityInfoEntity.getModel()));
                    returnData.add(jsonObject);
                }
            }
        }
        return returnData;
    }

    @ApiOperation("随机生成第三方客户")
    @GetMapping("/client/new")
    @CrossOrigin(origins = "*", maxAge = 86400)
    public JSONObject createClient(){
        JSONObject returnData = new JSONObject();
        String client = "client"+System.currentTimeMillis()+RandomStringUtils.randomAlphabetic(4);
        EntityWrapperHandle<ClientInfoEntity> ew0 = new EntityWrapperHandle<>();
        ew0.orderDesc(Collections.singletonList("id"));
        ew0.last("limit 1");
        List<ClientInfoEntity> clientList = clientService.selectList(ew0);
        String token;
        if(clientList!=null&&clientList.size()>0){
            token = createToken(clientList.get(0).getId()+1);
        }else{
            token = createToken(1);
        }
        returnData.put("client",client);
        returnData.put("token",token);
        return returnData;
    }

    @ApiOperation("增加第三方客户")
    @PostMapping("/client")
    @CrossOrigin(origins = "*", maxAge = 86400)
    public JSONObject addClient(@RequestBody JSONObject data){
        JSONObject returnData = new JSONObject();
        if(data!=null&&data.size()>0){
            String client = data.getString("client");
            String token = data.getString("token");
            if(isExist(client)&&isExist(token)){
                EntityWrapperHandle<ClientInfoEntity> ew0 = new EntityWrapperHandle<>();
                ew0.eq("clientname",client);
                List<ClientInfoEntity> list = clientService.selectList(ew0);
                if(list==null||list.size()==0){
                    ClientInfoEntity clientInfoEntity = new ClientInfoEntity();
                    clientInfoEntity.setToken(token);
                    clientInfoEntity.setClientname(client);
                    String remarks = data.getString("remarks");
                    if(remarks!=null){
                        clientInfoEntity.setRemarks(remarks);
                    }
                    JSONArray devices = data.getJSONArray("devices");
                    if(devices!=null){
                        clientInfoEntity.setRelationdevice(devices.toJSONString());
                    }
                    clientService.insert(clientInfoEntity);
                    EntityWrapperHandle<ClientInfoEntity> ew = new EntityWrapperHandle<>();
                    ew.eq("clientname",client);
                    List<ClientInfoEntity> user = clientService.selectList(ew);
                    if(user!=null&&user.size()>0){
                        returnData.put("id",user.get(0).getId());
                    }else{
                        returnData.put("message","创建失败");
                    }
                }else{
                    returnData.put("message","客户已存在");
                }
            }else{
                returnData.put("message","客户名或token不存在");
            }
        }else{
            returnData.put("message","参数不存在");
        }
        return returnData;
    }

    @ApiOperation("删除第三方客户")
    @DeleteMapping("/client")
    @CrossOrigin(origins = "*", maxAge = 86400)
    public JSONObject deleteClient(@RequestParam Map<String, String> data){
        JSONObject returnData = new JSONObject();
        if(data!=null&&data.size()>0){
            String sid = data.get("id");
            if(isExist(sid)&&isInteger(sid)){
                int id = Integer.parseInt(sid);
                if(id>0){
                    ClientInfoEntity client = clientService.selectById(id);
                    if(client!=null){
                        if(clientService.deleteById(id)){
                            returnData.put("code",200);
                        }else{
                            returnData.put("message", "删除失败");
                        }
                    }else{
                        returnData.put("message", "客户不存在");
                    }
                }else{
                    returnData.put("message", "参数错误");
                }
            }else{
                returnData.put("message", "参数不存在");
            }
        }else{
            returnData.put("message", "参数不存在");
        }
        return returnData;
    }

    @ApiOperation("修改第三方客户")
    @PutMapping("/client")
    @CrossOrigin(origins = "*", maxAge = 86400)
    public JSONObject changeClient(@RequestBody JSONObject data){
        JSONObject returnData = new JSONObject();
        if(data!=null&&data.size()>0){
            int id = data.getIntValue("id");
            if(id>0){
                ClientInfoEntity client = clientService.selectById(id);
                if(client!=null){
                    String remarks = data.getString("remarks");
                    if(remarks!=null){
                        client.setRemarks(remarks);
                    }
                    JSONArray devices = data.getJSONArray("devices");
                    if(devices!=null){
                        client.setRelationdevice(devices.toJSONString());
                    }
                    if(clientService.updateById(client)){
                        returnData.put("code",200);
                    }else{
                        returnData.put("message", "修改失败");
                    }
                }else{
                    returnData.put("message", "客户不存在");
                }
            }else{
                returnData.put("message", "参数错误");
            }
        }else{
            returnData.put("message", "参数不存在");
        }
        return returnData;
    }

    @ApiOperation("获取第三方客户")
    @GetMapping("/client")
    @CrossOrigin(origins = "*", maxAge = 86400)
    public JSONObject getClient(@RequestParam Map<String, String> data){
        JSONObject returnData = new JSONObject();
        if(data!=null&&data.size()>0){
            String sid = data.get("id");
            if(isExist(sid)&&isInteger(sid)){
                int id = Integer.parseInt(sid);
                if(id>0){
                    ClientInfoEntity client = clientService.selectById(id);
                    if(client!=null){
                        returnData.put("id",client.getId());
                        returnData.put("client",client.getClientname());
                        returnData.put("token",client.getToken());
                        returnData.put("remarks",client.getRemarks());
                        returnData.put("devices",JSONArray.parseArray(client.getRelationdevice()));
                    }else{
                        returnData.put("message", "客户不存在");
                    }
                }else{
                    returnData.put("message", "参数错误");
                }
            }else{
                returnData.put("message", "参数不存在");
            }
        }else{
            returnData.put("message", "参数不存在");
        }
        return returnData;
    }

    @ApiOperation("获取第三方客户")
    @GetMapping("/client/list")
    @CrossOrigin(origins = "*", maxAge = 86400)
    public JSONArray getClientList(){
        JSONArray returnData = new JSONArray();
        List<ClientInfoEntity> list = clientService.selectList(new EntityWrapperHandle<>());
        if(list!=null&&list.size()>0){
            for(ClientInfoEntity client : list){
                JSONObject jsonObject =new JSONObject();
                jsonObject.put("id",client.getId());
                jsonObject.put("client",client.getClientname());
                jsonObject.put("token",client.getToken());
                jsonObject.put("remarks",client.getRemarks());
                jsonObject.put("devices",JSONArray.parseArray(client.getRelationdevice()));
                returnData.add(jsonObject);
            }
        }
        return returnData;
    }

    private JSONArray getJsonAuthority(AdmininfoEntity admin) {
        JSONArray jsonArray = new JSONArray();

        JSONObject aty1 = new JSONObject();
        aty1.put("id", 1);
        aty1.put("enable", admin.getAuthority1());
        jsonArray.add(aty1);

        JSONObject aty2 = new JSONObject();
        aty2.put("id", 2);
        aty2.put("enable", admin.getAuthority2());
        jsonArray.add(aty2);

        JSONObject aty3 = new JSONObject();
        aty3.put("id", 3);
        aty3.put("enable", admin.getAuthority3());
        jsonArray.add(aty3);

        JSONObject aty4 = new JSONObject();
        aty4.put("id", 4);
        aty4.put("enable", admin.getAuthority4());
        jsonArray.add(aty4);

        JSONObject aty5 = new JSONObject();
        aty5.put("id", 5);
        aty5.put("enable", admin.getAuthority5());
        jsonArray.add(aty5);

        return jsonArray;
    }

    private void setJsonAuthority(AdmininfoEntity admin, JSONArray aty) {
        for (int i = 0; i < aty.size(); i++) {
            int id = aty.getJSONObject(i).getIntValue("id");
            int enable = aty.getJSONObject(i).getIntValue("enable");
            switch (id) {
                case 1: {
                    admin.setAuthority1(enable);
                    break;
                }
                case 2: {
                    admin.setAuthority2(enable);
                    break;
                }
                case 3: {
                    admin.setAuthority3(enable);
                    break;
                }
                case 4: {
                    admin.setAuthority4(enable);
                    break;
                }
                case 5: {
                    admin.setAuthority5(enable);
                    break;
                }
            }
        }
    }

    private JSONObject getAuthority(int aty, List<AuthorityInfoEntity> list) {
        JSONObject jsonObject = new JSONObject();
        for (AuthorityInfoEntity authorityInfoEntity : list) {
            if (authorityInfoEntity.getAid() == aty) {
                jsonObject.put("id", authorityInfoEntity.getAid());
                jsonObject.put("name", authorityInfoEntity.getName());
                jsonObject.put("description", authorityInfoEntity.getDescription());
                jsonObject.put("model", JSONArray.parseArray(authorityInfoEntity.getModel()));
                break;
            }
        }
        return jsonObject;
    }

    public boolean isExist(String value) {
        return value != null && !value.equals("");
    }

    public boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

    private String createToken(int id){
        String sid = String.valueOf(id);
        String mill = String.valueOf(System.currentTimeMillis());
        int count = 64-sid.length()-mill.length();
        String random = RandomStringUtils.randomAlphabetic(count);
        return sid+random+mill;
    }
}